package airthmetic.exercise.sort.cmp;


// 归并排序
public class _912_排序数组_Merge3 {
    int[] temp;

    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length < 2) {
            return nums;
        }
        mergeSort(nums, 0, nums.length - 1);
        return nums;
    }

    public void mergeSort(int[] nums, int left, int right) {
        // terminal
        if (left > right) {
            return;
        }

        int mid = (right + left) >> 1;
        // drill down
        mergeSort(nums, left, mid);
        mergeSort(nums, mid + 1, right);

        // process current logic
        // 合并两个数组
        int i = left;
        int j = mid + 1;
        int current = left;
        while (i <= mid && j <= right) {
            if (nums[i] < nums[j]) {
                temp[current++] = nums[i++];
            } else {
                temp[current++] = nums[j++];
            }
        }
        while (i <= mid) {
            temp[current++] = nums[i++];
        }
        while (j <= right) {
            temp[current++] = nums[j++];
        }

        for(int h = right - left; h<=right; h++){
            nums[h] = temp[h];
        }
    }
}
